package com.example.cardgame

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomnavigation.BottomNavigationView
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable

data class MyData(val score: Int) : Serializable
class GameFrame : Fragment() {
    lateinit var adapter:CardAdapter2
    private var callback: DataCallback? = null
    override fun onCreateView(
        inflater: LayoutInflater,container:ViewGroup?,savedInstanceState: Bundle?
    ):View?{
        return inflater.inflate(R.layout.activity_game_frame,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val rgame:CardMatchingGame2?=loadData()
        if(rgame!=null){
            game=rgame
        }else{
            game=CardMatchingGame2(24)
        }
        adapter=CardAdapter2(game)
        var recyclerView=view.findViewById<RecyclerView>(R.id.recycleView)
        recyclerView.adapter=adapter
        val configure=resources.configuration
        if(configure.orientation== Configuration.ORIENTATION_PORTRAIT){
            recyclerView.layoutManager= GridLayoutManager(activity,4)
        }else{
            recyclerView.layoutManager= GridLayoutManager(activity,6)
        }
        updateUI()
        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()
        }
        val recycle_button=view.findViewById<Button>(R.id.recycle_button)
        recycle_button.setOnClickListener{
            val myDataObject = MyData(game.score)
//            bundle.putSerializable("score",myDataObject)
//            FrameLayout.arguments=bundle
            callback?.onDataReceived(myDataObject)
            game.reset()
            updateUI()
        }
    }
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 确保宿主Activity实现了DataCallback接口
        if (context is DataCallback) {
            callback = context as DataCallback
        } else {
            throw RuntimeException("$context must implement DataCallback")
        }
    }
    override fun onDetach() {
        super.onDetach()
        callback = null // 清理引用，避免内存泄漏
    }
    fun updateUI(){
        adapter.notifyDataSetChanged()
        val score_text=view?.findViewById<TextView>(R.id.score_text)
        score_text?.text=String.format("%d",game.score)
    }
    override fun onStop(){
        super.onStop()
        saveData()
    }
    fun saveData(){
        try {
            val output: FileOutputStream?=activity?.openFileOutput("data2",AppCompatActivity.MODE_PRIVATE)
            val objectOutputStream= ObjectOutputStream(output)
            objectOutputStream.writeObject(game)
            objectOutputStream.close()
            output?.close()
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    fun loadData():CardMatchingGame2?{
        try {
            val input: FileInputStream?=activity?.openFileInput("data2")
            val objectInputStream= ObjectInputStream(input)
            val game:CardMatchingGame2=objectInputStream.readObject() as CardMatchingGame2
            objectInputStream.close()
            input?.close()
            return game
        }catch (e:Exception){
            e.printStackTrace()
            return null
        }
    }
    companion object{
        lateinit var game: CardMatchingGame2
        @JvmStatic
        fun newInstance():GameFrame=GameFrame()
    }
}